package edu.ynu.se.xiecheng.achitectureclass.service;

import edu.ynu.se.xiecheng.achitectureclass.common.service.LogicService;
import edu.ynu.se.xiecheng.achitectureclass.dao.PlantationDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.Plantation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Service
public class PlantationService extends LogicService<PlantationDao, Plantation, Long> {

    @PersistenceContext
    private EntityManager entityManager;

    public PlantationService(@Autowired PlantationDao dao) {
        super(dao);
    }

    /**
     * 查询单个大棚信息（包含设备信息）
     */
    public Plantation getPlantationInfo(Long id) throws Exception {
        return dao.findById(id)
                .orElseThrow(() -> new Exception("大棚不存在"));
    }

    /**
     * 更新大棚信息
     */
    public Plantation updatePlantation(Plantation plantation) throws Exception {
        // 获取原有种植园信息
        Plantation existingPlantation = dao.findById(plantation.getId())
                .orElseThrow(() -> new Exception("大棚不存在"));

        // 验证必填字段
        if (plantation.getPlantationName() == null || plantation.getPlantationName().trim().isEmpty()) {
            throw new Exception("大棚名称不能为空");
        }
        if (plantation.getPlantationAddress() == null || plantation.getPlantationAddress().trim().isEmpty()) {
            throw new Exception("大棚地址不能为空");
        }
        if (plantation.getPlantationArea() == null || plantation.getPlantationArea() <= 0) {
            throw new Exception("大棚面积必须大于0");
        }

        // 保留原有的逻辑删除字段值
        plantation.setIsDeleted(existingPlantation.getIsDeleted());
        plantation.setDeletedTime(existingPlantation.getDeletedTime());

        return dao.save(plantation);
    }
}